﻿@COFE ?= {}

$ = jQuery
Entry = COFE.Entry
EntryMeta = COFE.EntryMeta

class EntryMetaItem extends Spine.Controller
  constructor : () ->   
    super        
    
  elements :
    ".workIndicator" : "workIndicator"
    ".label" : "label"   

  init: ->     
    #generate entry or id, based on the another property.
    @entry ?= Entry.fromId(@id)    
    @id ?= @entry?.id

  fetch : =>
    if @entry isnt undefined
      linkMeta = @entry.links["metadata"]
      if linkMeta is undefined then (
        @meta = EntryMeta.fromJson(@id, {})
        @trigger("fetched", @)
      )
      else 
        $.get(linkMeta.url + "?" + COFE.jsonAtb)
          .success((data) =>
            @meta = EntryMeta.fromJson(@id, data)              
            @trigger("fetched", @)
        )
        .error((jqXHR, error) =>          
          @meta = EntryMeta.fromJson(@id, {})
          @trigger("error", @, error)
        )


  render: =>    
    @remove    
    for key of @meta.data
      @el.append(@template({ key : key, value : @meta.data[key] }))  
    @el   
  
  remove: =>
    @el.remove()

  template: (keyValue) ->    
    $(@templateKey).tmpl(keyValue)
  

COFE.EntryMetaItem = EntryMetaItem